package com.dao.c.backend.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Map;
import java.util.TimeZone;

@Component
public class JWTUtil {
    @Value("${SIGNATURE}")
    private static String SIGNATURE;

    @Value("${SIGNATURE}")
    public void setSIGNATURE(String signature){
        JWTUtil.SIGNATURE = signature;
    }

    /**
     * @param map //传入payload
     * @return 返回token
     * @description 生成token
     * @author 张幸晔
     * @date 2025-02-25 09:11
     */

    public static String buildToken(Map<String,String>map)  {
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        Calendar instance = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
        instance.add(Calendar.DATE,10);//默认10天过期
        builder.withExpiresAt(instance.getTime());//指定令牌的过期时间
        return builder.sign(Algorithm.HMAC256(SIGNATURE)).toString();
    }
    /**
     * @param token
     * @return
     * @description 验证token
     * @author 张幸晔
     * @date 2025-02-25 09:15
     */

    public static void verify(String token) {
        if (token == null || token.trim().isEmpty()) {
            throw new IllegalArgumentException("Token is null or empty");
        }
        JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }
    /**
     * @param token
     * @return
     * @description 获取token
     * @author 张幸晔
     * @date 2025-02-25 09:15
     */

    public static DecodedJWT getToken(String token) {
        if (token == null || token.trim().isEmpty()) {
            throw new IllegalArgumentException("Token is null or empty");
        }
        return JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }
}
